package net.oschina.esb;

import net.oschina.esb.core.env.EsbContext;
import org.junit.runners.model.InitializationError;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.context.support.GenericWebApplicationContext;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Arvin
 * @time 2018/4/11 20:59
 */
public class EsbRunner extends SpringJUnit4ClassRunner {
    /**
     * Construct a new {@code SpringJUnit4ClassRunner} and initialize a
     * {@link TestContextManager} to provide Spring testing functionality to
     * standard JUnit tests.
     *
     * @param clazz the test class to be run
     * @see #createTestContextManager(Class)
     */
    public EsbRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
        try {
            EsbContext.initEnv(clazz, new String[]{}, false);
        } catch (IOException e) {
            e.printStackTrace();
        }

        GenericWebApplicationContext applicationContext = (GenericWebApplicationContext) getTestContextManager().getTestContext().getApplicationContext();

        EsbContext.setEnvironment(applicationContext.getEnvironment());

        StandardEnvironment environment = (StandardEnvironment) applicationContext.getEnvironment();

        MutablePropertySources propertySources = environment.getPropertySources();


        propertySources.addFirst(new MapPropertySource("apppros", getMapFromProperties(EsbContext.getAppProperties())));

        System.out.println(propertySources);
        EsbContext.setApplicationContext(applicationContext);
    }

    private Map<String, Object> getMapFromProperties(Properties properties) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        for (Object key : Collections.list(properties.propertyNames())) {
            map.put((String) key, properties.get(key));
        }
        return map;
    }

    @Override
    protected Object createTest() throws Exception {
        Object test = super.createTest();

        System.out.println(test);

        return test;
    }
}
